package tcpdemo;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class TcpClientDemo1 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;

        try {
            // 1. 要知道服务器的地址，端口号
            InetAddress serverIp = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            // 2. 创建一个socket连接
            socket = new Socket(serverIp, port);
            // 3. 发送消息 IO流
            os = socket.getOutputStream();
            os.write("你好，欢迎学习狂神说java".getBytes());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 4. 关闭资源
            try {
                assert os != null;
                os.close();  // 关闭输出流
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();  // 关闭socket
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
